<template>
  <Dialog v-model="dialogVisible" title="选择链接" width="65%">
    <div class="h-500px flex gap-8px">
      <!-- 左侧分组列表 -->
      <el-scrollbar wrap-class="h-full" ref="groupScrollbar" view-class="flex flex-col">
        <el-button
          v-for="(group, groupIndex) in APP_LINK_GROUP_LIST"
          :key="groupIndex"
          :class="[
            'm-r-16px m-l-0px! justify-start! w-90px',
            { active: activeGroup === group.name }
          ]"
          ref="groupBtnRefs"
          :text="activeGroup !== group.name"
          :type="activeGroup === group.name ? 'primary' : 'default'"
          @click="handleGroupSelected(group.name)"
        >
          {{ group.name }}
        </el-button>
      </el-scrollbar>
      <!-- 右侧链接列表 -->
      <el-scrollbar class="h-full flex-1" @scroll="handleScroll" ref="linkScrollbar">
        <div v-for="(group, groupIndex) in APP_LINK_GROUP_LIST" :key="groupIndex">
          <!-- 分组标题 -->
          <div class="font-bold" ref="groupTitleRefs">{{ group.name }}</div>
          <!-- 链接列表 -->
          <el-tooltip
            v-for="(appLink, appLinkIndex) in group.links"
            :key="appLinkIndex"
            :content="getTooltipContent(appLink)"
            placement="bottom"
            :show-after="300"
          >
            <el-button
              class="m-b-8px m-r-8px m-l-0px!"
              :type="isAppLinkSelected(appLink) ? 'primary' : 'default'"
              @click="handleAppLinkSelected(appLink)"
            >
              {{ getButtonText(appLink) }}
            </el-button>
          </el-tooltip>
        </div>
      </el-scrollbar>
    </div>
    <!-- 底部对话框操作按钮 -->
    <template #footer>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <Dialog v-model="detailSelectDialog.visible" title="" width="50%">
    <el-form class="min-h-200px">
      <el-form-item
        label="选择分类"
        v-if="detailSelectDialog.type === APP_LINK_TYPE_ENUM.PRODUCT_CATEGORY_LIST"
      >
        <ProductCategorySelect
          v-model="detailSelectDialog.id"
          :parent-id="0"
          @update:model-value="handleProductCategorySelected"
        />
      </el-form-item>
      <el-form-item
        label="选择智能体角色"
        v-if="detailSelectDialog.type === APP_LINK_TYPE_ENUM.AI_AGENT_ROLES"
      >
        <RoleCategorySelect
          @update:model-value="handleAgentRoleSelected"
          v-model="detailSelectDialog.id" />
      </el-form-item>

    </el-form>
  </Dialog>
  
  <!-- 商品选择弹窗 -->
  <SpuTableSelect ref="spuSelectRef" @change="handleSpuSelected" />
  
  <!-- 文章选择弹窗 -->
  <ArticleTableSelect ref="articleSelectRef" @change="handleArticleSelected" />
  
  <!-- 退款活动选择弹窗 -->
  <RefundActivityTableSelect ref="refundActivitySelectRef" @change="handleRefundActivitySelected" />
  
  <!-- 自定义页面输入弹窗 -->
  <Dialog v-model="customPageDialog.visible" title="自定义页面" width="50%">
    <el-form class="min-h-200px">
      <el-form-item label="页面路径" required>
        <el-input
          v-model="customPageDialog.path"
          placeholder="请输入页面路径，如：/pages/custom/index 或完整链接"
          clearable
        />
        <div class="text-gray-500 text-sm mt-1">
          支持相对路径（如：/pages/custom/index）或完整链接（如：https://example.com）
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="handleCustomPageSubmit">确 定</el-button>
      <el-button @click="customPageDialog.visible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { APP_LINK_GROUP_LIST, APP_LINK_TYPE_ENUM, AppLink } from './data'
import { ButtonInstance, ScrollbarInstance } from 'element-plus'
import { split } from 'lodash-es'
import ProductCategorySelect from '@/views/mall/product/category/components/ProductCategorySelect.vue'
import { getUrlNumberValue } from '@/utils'
import RoleCategorySelect from '@/views/ai/chat/index/components/role/RoleCategorySelect.vue'
import SpuTableSelect from '@/views/mall/product/spu/components/SpuTableSelect.vue'
import ArticleTableSelect from '@/views/mall/promotion/article/components/ArticleTableSelect.vue'
import RefundActivityTableSelect from '@/views/mall/promotion/refund/rule/components/RefundActivityTableSelect.vue'


// APP 链接选择弹框
defineOptions({ name: 'AppLinkSelectDialog' })
// 选中的分组，默认选中第一个
const activeGroup = ref(APP_LINK_GROUP_LIST[0].name)
// 选中的 APP 链接
const activeAppLink = ref({} as AppLink)
// 商品选择组件引用
const spuSelectRef = ref()
// 文章选择组件引用
const articleSelectRef = ref()
// 退款活动选择组件引用
const refundActivitySelectRef = ref()

// 自定义页面对话框
const customPageDialog = ref<{
  visible: boolean
  path: string
}>({
  visible: false,
  path: ''
})

/** 打开弹窗 */
const dialogVisible = ref(false)
const open = (link: string) => {
  activeAppLink.value.path = link
  dialogVisible.value = true

  // 滚动到当前的链接
  const group = APP_LINK_GROUP_LIST.find((group) =>
    group.links.some((linkItem) => {
      const sameLink = isSameLink(linkItem.path, link)
      if (sameLink) {
        activeAppLink.value = { ...linkItem, path: link }
      }
      return sameLink
    })
  )
  
  // 如果没有找到匹配的链接，检查是否是商品相关路径
  if (!group && link.includes('/pages/goods/')) {
    // 查找商品详情按钮
    const productGroup = APP_LINK_GROUP_LIST.find(g => g.name === '商品')
    if (productGroup) {
      const productDetailLink = productGroup.links.find(l => l.type === APP_LINK_TYPE_ENUM.PRODUCT_DETAIL_NORMAL)
      if (productDetailLink) {
        activeAppLink.value = { ...productDetailLink, path: link }
        // 使用 nextTick 的原因：可能 Dom 还没生成，导致滚动失败
        nextTick(() => handleGroupSelected(productGroup.name))
        return
      }
    }
  }
  
  if (group) {
    // 使用 nextTick 的原因：可能 Dom 还没生成，导致滚动失败
    nextTick(() => handleGroupSelected(group.name))
  }
}
defineExpose({ open })

// 处理 APP 链接选中
const handleAppLinkSelected = (appLink: AppLink) => {
  if (!isSameLink(appLink.path, activeAppLink.value.path)) {
    activeAppLink.value = appLink
  }
  switch (appLink.type) {
    case APP_LINK_TYPE_ENUM.PRODUCT_CATEGORY_LIST:
      detailSelectDialog.value.visible = true
      detailSelectDialog.value.type = appLink.type
      // 返显
      detailSelectDialog.value.id =
        getUrlNumberValue('id', 'http://127.0.0.1' + activeAppLink.value.path) || undefined
      break
    case APP_LINK_TYPE_ENUM.AI_AGENT_ROLES:
      detailSelectDialog.value.visible = true
      detailSelectDialog.value.type = appLink.type
      detailSelectDialog.value.id=undefined
      break
    case APP_LINK_TYPE_ENUM.PRODUCT_DETAIL_NORMAL:
      // 只有普通商品详情才打开商品选择弹窗
      spuSelectRef.value?.open()
      break
    case APP_LINK_TYPE_ENUM.PRODUCT_DETAIL_COMBINATION:
    case APP_LINK_TYPE_ENUM.PRODUCT_DETAIL_SECKILL:
      // 拼团商品详情和秒杀商品详情不打开弹窗，保持原有路径
      break
    case APP_LINK_TYPE_ENUM.ARTICLE_DETAIL:
      // 直接打开文章选择弹窗
      articleSelectRef.value?.open()
      break
    case APP_LINK_TYPE_ENUM.ACTIVITY_REFUND:
      // 直接打开退款活动选择弹窗
      refundActivitySelectRef.value?.open()
      break
    case APP_LINK_TYPE_ENUM.DIY_PAGE_DETAIL:
      // 直接打开自定义页面输入弹窗
      customPageDialog.value.visible = true
      customPageDialog.value.path = activeAppLink.value.path || ''
      break
    default:
      break
  }
}

// 处理绑定值更新
const emit = defineEmits<{
  change: [link: string]
  appLinkChange: [appLink: AppLink]
}>()
const handleSubmit = () => {
  dialogVisible.value = false
  emit('change', activeAppLink.value.path)
  emit('appLinkChange', activeAppLink.value)
}

// 分组标题引用列表
const groupTitleRefs = ref<HTMLInputElement[]>([])
/**
 * 处理右侧链接列表滚动
 * @param scrollTop 滚动条的位置
 */
const handleScroll = ({ scrollTop }: { scrollTop: number }) => {
  const titleEl = groupTitleRefs.value.find((titleEl: HTMLInputElement) => {
    // 获取标题的位置信息
    const { offsetHeight, offsetTop } = titleEl
    // 判断标题是否在可视范围内
    return scrollTop >= offsetTop && scrollTop < offsetTop + offsetHeight
  })
  // 只需处理一次
  if (titleEl && activeGroup.value !== titleEl.textContent) {
    activeGroup.value = titleEl.textContent || ''
    // 同步左侧的滚动条位置
    scrollToGroupBtn(activeGroup.value)
  }
}

// 右侧滚动条
const linkScrollbar = ref<ScrollbarInstance>()
// 处理分组选中
const handleGroupSelected = (group: string) => {
  activeGroup.value = group
  const titleRef = groupTitleRefs.value.find((item: HTMLInputElement) => item.textContent === group)
  if (titleRef) {
    // 滚动分组标题
    linkScrollbar.value?.setScrollTop(titleRef.offsetTop)
  }
}

// 分组滚动条
const groupScrollbar = ref<ScrollbarInstance>()
// 分组引用列表
const groupBtnRefs = ref<ButtonInstance[]>([])
// 自动滚动分组按钮，确保分组按钮保持在可视区域内
const scrollToGroupBtn = (group: string) => {
  const groupBtn = groupBtnRefs.value
    .map((btn: ButtonInstance) => btn['ref'])
    .find((ref: HTMLButtonElement | undefined) => ref?.textContent === group)
  if (groupBtn) {
    groupScrollbar.value?.setScrollTop(groupBtn.offsetTop)
  }
}

// 是否为相同的链接（不比较参数，只比较链接）
const isSameLink = (link1: string, link2: string) => {
  return split(link1, '?', 1)[0] === split(link2, '?', 1)[0]
}

// 判断应用链接是否被选中
const isAppLinkSelected = (appLink: AppLink) => {
  // 对于普通商品详情，需要特殊处理
  if (appLink.type === APP_LINK_TYPE_ENUM.PRODUCT_DETAIL_NORMAL) {
    // 如果当前路径包含商品相关路径，则认为商品详情按钮被选中
    return activeAppLink.value.path && activeAppLink.value.path.includes('/pages/goods/')
  }
  // 其他类型使用原来的逻辑
  return isSameLink(appLink.path, activeAppLink.value.path)
}

// 获取按钮显示文本
const getButtonText = (appLink: AppLink) => {
  // 如果是普通商品详情类型且当前选中的链接是这个链接
  if (appLink.type === APP_LINK_TYPE_ENUM.PRODUCT_DETAIL_NORMAL &&
      isSameLink(appLink.path, activeAppLink.value.path)) {
    // 提取ID参数
    const id = getUrlNumberValue('id', 'http://127.0.0.1' + activeAppLink.value.path)
    if (id) {
      return `${appLink.name}-${id}`
    }
  }
  // 如果是普通商品详情类型且当前选中的链接是商品相关路径（包括 pages/goods/index 和 pages/goods/indexLocal）
  if (appLink.type === APP_LINK_TYPE_ENUM.PRODUCT_DETAIL_NORMAL &&
      activeAppLink.value.path && activeAppLink.value.path.includes('/pages/goods/')) {
    // 提取ID参数
    const id = getUrlNumberValue('id', 'http://127.0.0.1' + activeAppLink.value.path)
    if (id) {
      return `${appLink.name}-${id}`
    }
  }
  // 如果是文章详情类型且当前选中的链接是这个链接
  if (appLink.type === APP_LINK_TYPE_ENUM.ARTICLE_DETAIL &&
      isSameLink(appLink.path, activeAppLink.value.path)) {
    // 提取ID参数
    const id = getUrlNumberValue('id', 'http://127.0.0.1' + activeAppLink.value.path)
    if (id) {
      return `${appLink.name}-${id}`
    }
  }
  // 如果是退款活动类型且当前选中的链接是这个链接
  if (appLink.type === APP_LINK_TYPE_ENUM.ACTIVITY_REFUND &&
      isSameLink(appLink.path, activeAppLink.value.path)) {
    // 提取ID参数
    const id = getUrlNumberValue('id', 'http://127.0.0.1' + activeAppLink.value.path)
    if (id) {
      return `${appLink.name}-${id}`
    }
  }
  // 如果是自定义页面类型且当前选中的链接是这个链接
  if (appLink.type === APP_LINK_TYPE_ENUM.DIY_PAGE_DETAIL &&
      isSameLink(appLink.path, activeAppLink.value.path)) {
    // 显示路径的简化版本（取最后一段或前20个字符）
    const path = activeAppLink.value.path
    if (path && path !== appLink.path) {
      const pathSegments = path.split('/')
      const lastSegment = pathSegments[pathSegments.length - 1] || pathSegments[pathSegments.length - 2]
      const displayText = lastSegment || path.substring(0, 20) + (path.length > 20 ? '...' : '')
      return `${appLink.name}-${displayText}`
    }
  }
  return appLink.name
}

// 获取tooltip内容
const getTooltipContent = (appLink: AppLink) => {
  // 如果是普通商品详情类型且当前选中的链接是这个链接
  if (appLink.type === APP_LINK_TYPE_ENUM.PRODUCT_DETAIL_NORMAL &&
      isSameLink(appLink.path, activeAppLink.value.path)) {
    // 返回包含参数的完整路径
    return activeAppLink.value.path
  }
  // 如果是普通商品详情类型且当前选中的链接是商品相关路径（包括 pages/goods/index 和 pages/goods/indexLocal）
  if (appLink.type === APP_LINK_TYPE_ENUM.PRODUCT_DETAIL_NORMAL &&
      activeAppLink.value.path && activeAppLink.value.path.includes('/pages/goods/')) {
    // 返回包含参数的完整路径
    return activeAppLink.value.path
  }
  // 如果是文章详情类型且当前选中的链接是这个链接
  if (appLink.type === APP_LINK_TYPE_ENUM.ARTICLE_DETAIL &&
      isSameLink(appLink.path, activeAppLink.value.path)) {
    // 返回包含参数的完整路径
    return activeAppLink.value.path
  }
  // 如果是退款活动类型且当前选中的链接是这个链接
  if (appLink.type === APP_LINK_TYPE_ENUM.ACTIVITY_REFUND &&
      isSameLink(appLink.path, activeAppLink.value.path)) {
    // 返回包含参数的完整路径
    return activeAppLink.value.path
  }
  // 如果是自定义页面类型且当前选中的链接是这个链接
  if (appLink.type === APP_LINK_TYPE_ENUM.DIY_PAGE_DETAIL &&
      isSameLink(appLink.path, activeAppLink.value.path)) {
    // 返回完整的自定义路径
    return activeAppLink.value.path
  }
  return appLink.path
}

// 详情选择对话框
const detailSelectDialog = ref<{
  visible: boolean
  id?: number
  type?: APP_LINK_TYPE_ENUM
}>({
  visible: false,
  id: undefined,
  type: undefined
})
const handleAgentRoleSelected=(id: number)=>{
  const url = new URL(activeAppLink.value.path, 'http://127.0.0.1')
  // 修改 id 参数
  url.searchParams.set('id', `${id}`)
  // 排除域名
  activeAppLink.value.path = `${url.pathname}${url.search}`
  // 关闭对话框
  detailSelectDialog.value.visible = false
  // 重置 id
  detailSelectDialog.value.id = undefined
}
// 处理详情选择
const handleProductCategorySelected = (id: number) => {
  const url = new URL(activeAppLink.value.path, 'http://127.0.0.1')
  // 修改 id 参数
  url.searchParams.set('id', `${id}`)
  // 排除域名
  activeAppLink.value.path = `${url.pathname}${url.search}`
  // 关闭对话框
  detailSelectDialog.value.visible = false
  // 重置 id
  detailSelectDialog.value.id = undefined
}

// 处理商品选择
const handleSpuSelected = (spu: any) => {
  // 使用商品对象中的路径信息，如果没有则使用当前路径
  const basePath = spu.path || activeAppLink.value.path
  const url = new URL(basePath, 'http://127.0.0.1')
  // 修改 id 参数
  url.searchParams.set('id', `${spu.id}`)
  // 排除域名
  activeAppLink.value.path = `${url.pathname}${url.search}`
}

// 处理文章选择
const handleArticleSelected = (article: any) => {
  const url = new URL(activeAppLink.value.path, 'http://127.0.0.1')
  // 修改 id 参数
  url.searchParams.set('id', `${article.id}`)
  // 排除域名
  activeAppLink.value.path = `${url.pathname}${url.search}`
}

// 处理退款活动选择
const handleRefundActivitySelected = (activity: any) => {
  const url = new URL(activeAppLink.value.path, 'http://127.0.0.1')
  // 修改 id 参数
  url.searchParams.set('id', `${activity.id}`)
  // 排除域名
  activeAppLink.value.path = `${url.pathname}${url.search}`
}

// 处理自定义页面提交
const handleCustomPageSubmit = () => {
  if (!customPageDialog.value.path.trim()) {
    return
  }
  // 直接使用用户输入的路径
  activeAppLink.value.path = customPageDialog.value.path.trim()
  // 关闭对话框
  customPageDialog.value.visible = false
  customPageDialog.value.path = ''
}
</script>
<style lang="scss" scoped></style>
